package com.example.parking.service;/*
 * @author 陈政
 * @date 2020-08-12 19:18
 */

import com.alibaba.fastjson.JSONObject;
import mapper.BsProvinceMapper;
import mapper.ParkingMapper;
import mapper.PropertyMapper;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.WildcardQueryBuilder;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.Query;
import org.springframework.transaction.annotation.Transactional;
import pojo.Property;
import vo.CreateParkingVo;
import vo.HomeParkingVo;
import com.github.pagehelper.PageInfo;
import entity.PageParam;
import entity.Rsp;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.core.CountRequest;
import org.elasticsearch.client.core.CountResponse;
import org.elasticsearch.index.query.QueryBuilder;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import pojo.Parking;
import pojo.ParkingInfo;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.*;

@Service
@Transactional
public class ParkingServiceImpl implements ParkingService{

    @Autowired
    ParkingMapper parkingMapper;
    @Autowired
    PropertyMapper propertyMapper;
    @Autowired
    BsProvinceMapper bsProvinceMapper;
    @Autowired
    ParkingEsService parkingEsService;
    @Autowired
    RestHighLevelClient restHighLevelClient;
    @Autowired
    RabbitTemplate rabbitTemplate;


    /**
     * @Author 陈政
     * @Description 删除车位测试
     * @Date 15:37 2020-08-25
     * @Param [parkingId]
     * @return int
     **/
    @Override
    public int deleteByPrimaryKey(String parkingId) {
        return 0;
    }

    /**
     * @Author 陈政
     * @Description 插入一条车位测试
     * @Date 15:40 2020-08-25
     * @Param [record]
     * @return int
     **/
    @Override
    public int insert(Parking record) {
        System.out.println(parkingMapper+"---");
        int i = parkingMapper.insert(record);
        return i;
    }

    /**
     * @Author 陈政
     * @Description 条件增加车位
     * @Date 15:40 2020-08-25
     * @Param [record]
     * @return int
     **/
    @Override
    public int insertSelective(Parking record) {

        return 0;
    }

    /**
     * @Author 陈政
     * @Description 根据parkingId查找车位详细信息
     * @Date 15:41 2020-08-25
     * @Param [parkingId]
     * @return vo.HomeParkingVo
     **/
    @Override
    @Transactional(readOnly = true)
    public HomeParkingVo selectByPrimaryKey(String parkingId) {
        //根据parkingId查找一条parking
        HomeParkingVo homeParkingVo = parkingMapper.selectByPrimaryKey(parkingId);
        return homeParkingVo;

    }

    /**
     * @Author 陈政
     * @Description 根据车位Id条件修改车位
     * @Date 15:42 2020-08-25
     * @Param [record]
     * @return int
     *
     * @param record*/
    @Override
    public int updateByPrimaryKeySelective(PageParam<Parking> record) {
        System.out.println("开始修改");
        Parking parking = record.getModel();
        String status = record.getSuperSearchKeyWord();
        parking.setIsDeleted(Integer.parseInt(status));

        parkingMapper.updateByPrimaryKeySelective(parking);

        HomeParkingVo homeParkingVo1 = parkingMapper.selectByPrimaryKey(parking.getParkingId());
        System.out.println(homeParkingVo1);

        parkingEsService.save(homeParkingVo1);
        HomeParkingVo homeParkingVo2 = parkingEsService.queryHomeParkingVoByParkingId(parking.getParkingId());
        System.out.println(homeParkingVo2);

        return 0;
    }

    /**
     * @Author 陈政
     * @Description 根据车位Id修改车位
     * @Date 15:42 2020-08-25
     * @Param [record]
     * @return int
     **/
    @Override
    public int updateByPrimaryKeyWithBLOBs(Parking record) {
        return 0;
    }

    /**
     * @Author 陈政
     * @Description 根据主键修改车位
     * @Date 15:43 2020-08-25
     * @Param [record]
     * @return int
     **/
    @Override
    public int updateByPrimaryKey(Parking record) {
        return 0;
    }

    /**
     * @Author 陈政
     * @Description 分页查找、模糊查询车位
     * @Date 15:46 2020-08-25
     * @Param [pageParam]
     * @return com.github.pagehelper.PageInfo<vo.HomeParkingVo>
     **/
    @Override
    @Transactional(readOnly = true)
    public PageInfo<HomeParkingVo> searchSomeByPage(String userId, PageParam<Parking> pageParam) {
        System.out.println("开始查询");

        System.out.println(userId);
        //如果关键字为findmyparkings则变成条件搜索
        Query query;
        if(pageParam.getSuperSearchKeyWord().equalsIgnoreCase("findmyparkings")){
            BoolQueryBuilder bqb = QueryBuilders.boolQuery();
            bqb.must(QueryBuilders.matchPhraseQuery("rentId", "85d0137d0a9442809215827dc3f12838")).mustNot(QueryBuilders.matchPhraseQuery("isDeleted", "1"));
            query = new NativeSearchQueryBuilder().withQuery(bqb).withPageable(PageRequest.of(pageParam.getPageNum()-1, pageParam.getPageSize())).build();
        }else {
            // 模糊查询 name字段  name中包含字母o的数据
            WildcardQueryBuilder wqb = QueryBuilders.wildcardQuery("propertyName", "*"+pageParam.getSuperSearchKeyWord()+"*");

            BoolQueryBuilder bqb = QueryBuilders.boolQuery();
            bqb.must(QueryBuilders.matchPhraseQuery("isDeleted", "0")).must(wqb);

            //PageRequest.of(page页数，size每页的数据量)
            query = new NativeSearchQueryBuilder().withQuery(bqb).withPageable(PageRequest.of(pageParam.getPageNum()-1, pageParam.getPageSize())).build();
        }

        Page<HomeParkingVo> homeParkingVoPage = parkingEsService.search(query);
        List<HomeParkingVo> content = homeParkingVoPage.getContent();
            content.forEach(parking -> {
                //查询用户手机号
                String phone = parking.getPhone();
                String phoneNumber = phone.substring(0, 3) + "****" + phone.substring(7, phone.length());
                //格式化日期
                SimpleDateFormat f = new SimpleDateFormat("yyyy年MM月dd日 HH点mm分ss秒");
                parking.setPhone(phoneNumber);
                parking.setCreateTimeFormat(f.format(parking.getCreateTime()));
            });
            PageInfo<HomeParkingVo> parkingPageInfo = new PageInfo<HomeParkingVo>(content);
            return parkingPageInfo;
    }

    /**
     * @Author 陈政
     * @Description 查询省份
     * @Date 15:46 2020-08-25
     * @Param []
     * @return java.util.List
     **/
    @Override
    @Transactional(readOnly = true)
    public List getProvinces() {
        List<String> provinceName = bsProvinceMapper.selectAllShortName();
        System.out.println(provinceName);
        return provinceName;
    }

    /**
     * @Author 陈政
     * @Description 查询物业信息
     * @Date 15:46 2020-08-25
     * @Param []
     * @return java.util.List
     **/
    @Override
    @Transactional(readOnly = true)
    public List getProperties() {
        List<Property> allPropertyName = propertyMapper.getAllPropertyName();
        return allPropertyName;
    }

    /**
     * @Author 陈政
     * @Description 增加车位
     * @Date 15:47 2020-08-25
     * @Param [createParkingVo]
     * @return entity.Rsp
     **/
    @Override
    public Rsp createParking(CreateParkingVo createParkingVo) {

        Parking parking = new Parking();
        BeanUtils.copyProperties(createParkingVo, parking);

        //字符串转换为Long
        parking.setRentMoney(Long.parseLong(createParkingVo.getRentMoney()));

        //生成uuid
        String id = UUID.randomUUID().toString().replace("-","");
        parking.setParkingId(id);

        //设置userId
        parking.setRentId("85d0137d0a9442809215827dc3f12838");

        //设置创建时间
        Date date = new Date();

        parking.setCreateTime(date);

        //逻辑删除字段初始值为2
        parking.setIsDeleted(2);

        int insert = parkingMapper.insert(parking);

        //增加parkingInfo数据
        ParkingInfo parkingInfo = new ParkingInfo();
        parkingInfo.setParkingImg("2020-08-21-16-09-34.jpg");
        parkingInfo.setParkingId(id);

        if(insert == 1){
            createParkingInfo(parkingInfo);
            String s = JSONObject.toJSONString(parking);
            rabbitTemplate.convertAndSend("airparking_parking","parking.create",s);
            return Rsp.success(id);
        }

        return Rsp.fail();


    }

    /**
     * @Author 陈政
     * @Description 查找车位数量
     * @Date 15:47 2020-08-25
     * @Param []
     * @return java.lang.Integer
     **/
    @Override
    @Transactional(readOnly = true)
    public Integer getCounts() {

        WildcardQueryBuilder propertyName = QueryBuilders.wildcardQuery("propertyName", "**");

        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.matchPhraseQuery("isDeleted", "0")).must(propertyName);

        long count = count("homeparkingvo", bqb);

        return (int)count;
    }

    /**
     * @Author 陈政
     * @Description 模糊查询查找车位数量
     * @Date 15:47 2020-08-25
     * @Param [pageParam]
     * @return java.lang.Integer
     **/
    @Override
    @Transactional(readOnly = true)
    public Integer getCountsWithKey(PageParam<Parking> pageParam) {
        WildcardQueryBuilder propertyName = QueryBuilders.wildcardQuery("propertyName", "*"+pageParam.getSuperSearchKeyWord()+"*");

        BoolQueryBuilder bqb = QueryBuilders.boolQuery();
        bqb.must(QueryBuilders.matchPhraseQuery("isDeleted", "0")).must(propertyName);

        long count = count("homeparkingvo", bqb);

        return (int)count;
        //return parkingMapper.getCountsWithKey(pageParam.getSuperSearchKeyWord());

    }

    /**
     * @Author 陈政
     * @Description 增加车位详情
     * @Date 15:48 2020-08-25
     * @Param [parkingInfo]
     * @return int
     **/
    @Override
    public int createParkingInfo(ParkingInfo parkingInfo) {
        //生成uuid
        String id = UUID.randomUUID().toString().replace("-","");
        parkingInfo.setParkingInfoId(id);
        return parkingMapper.insertParkingInfo(parkingInfo);
    }

    /**
     * @Author 陈政
     * @Description 存储车位图片
     * @Date 15:48 2020-08-25
     * @Param [file]
     * @return java.util.Map
     **/
    @Override
    public Map saveImg(MultipartFile file) {
        String prefix="";
        String dateStr="";
        //保存上传
        OutputStream out = null;
        InputStream fileInput=null;
        try{
            if(file!=null){
                String originalName = file.getOriginalFilename();
                prefix=originalName.substring(originalName.lastIndexOf(".")+1);
                //格式化日期
                SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
                dateStr = f.format(new Date());
                //String id = UUID.randomUUID().toString().replace("-","");
                String filepath = "/Users/chen/Downloads/Airparking 2/img/" +dateStr + "." + prefix;
                File files=new File(filepath);
                //打印查看上传路径
                filepath = dateStr + "." + prefix;
                System.out.println(filepath);
                if(!files.getParentFile().exists()){
                    files.getParentFile().mkdirs();
                }
                file.transferTo(files);
            }
        }catch (Exception e){
        }finally{
            try {
                if(out!=null){
                    out.close();
                }
                if(fileInput!=null){
                    fileInput.close();
                }
            } catch (IOException e) {
            }
        }
        Map<String,Object> map2=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        map.put("code",0);
        map.put("msg","");

        map2.put("src","/Users/chen/Downloads/Airparking 2/img/" +dateStr + "." + prefix);
        map.put("data",map2);
        return map;
    }


    /*
     * @Author 陈政
     * @Description 查找es的条数
     * @Date 15:49 2020-08-25
     * @Param [idxName, builder]
     * @return long
     **/
    public long count(String idxName, QueryBuilder builder) {
        CountRequest countRequest=new CountRequest(idxName);
        countRequest.query(builder);
        try {
            CountResponse response=restHighLevelClient.count(countRequest, RequestOptions.DEFAULT);
            long length = response.getCount();
            return length;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
